<?php
namespace Modules;

use Admin\Models\school\XhschoolInfo;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserHistory;
use Helpers\Cache;
use Helpers\Main;
use Helpers\User;
use Helpers\XhException;

class School
{

    public static $enum = [
        'iStatus' => [0 => '未上线', 1 => '上线', 2 => '运营', 3 => '停用']
    ];

    /**
     * 获取学校列表
     *
     * @param bool $all
     * @return array|bool|mixed|null
     *
     * create by ck 20180612
     * modify by ck 20181229
     */
    public static function getSchools($all = false)
    {
        $cacheKey = $all ? 'school_list' : 'school_support';
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $params = [
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0'
        ];
        if (!$all) {
            $params['conditions'] .= ' AND (iStatus = 1 OR iStatus = 2)';
        }
        $schoolList = XhschoolInfo::find($params)->toArray();
        $schoolList = array_column($schoolList, 'sSchoolName', 'iSchoolId');
        Cache::save($cacheKey, $schoolList);
        return $schoolList;
    }

    /**
     * 通过地区名查找相关学校
     *
     * @param array $where
     * @return array
     *
     * create by sqb 20181219
     */
    public static function getSchoolsByArea($where = [])
    {
        $params = [
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0 AND (iStatus = 1 OR iStatus = 2)',
        ];

        if ($where && $where['province']) {
            $params['conditions'] .= ' AND sProvinceName = :province:';
            $params['bind']['province'] .= $where['province'];
        }

        if ($where && $where['city']) {
            $params['conditions'] .= ' AND sCityName = :city:';
            $params['bind']['city'] .= $where['city'];
        }

        if ($where && $where['county']) {
            $params['conditions'] .= ' AND sCountyName = :county:';
            $params['bind']['county'] .= $where['county'];
        }

        $schoolList = XhschoolInfo::find($params)->toArray();
        $schoolList = array_column($schoolList, 'sSchoolName', 'iSchoolId');

        return $schoolList;
    }

    /**
     * 获取学校编号
     *
     * @param bool $all
     * @return bool|mixed|null
     *
     * create by ck 20181016
     */
    public static function getCodes($all = false)
    {
        $cacheKey = $all ? 'school_code_list' : 'school_code_support';
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $params = [
            'columns'    => 'iSchoolId,sCode',
            'conditions' => 'bDelete = 0'
        ];
        if (!$all) {
            $params['conditions'] .= ' AND (iStatus = 1 OR iStatus = 2)';
        }
        $schoolList = XhschoolInfo::find($params)->toArray();
        Cache::save($cacheKey, array_column($schoolList, 'sCode', 'iSchoolId'));
        return $schoolList;
    }

    /**
     * 根据关键字匹配返回学校id
     *
     * @param $key
     * @param $all
     * @param $withName
     * @return array
     *
     * create by xjq 20180612
     */
    public static function searchSchool($key, $all = false, $withName = false)
    {
        $schools = self::getSchools($all);
        $machIds = [];
        foreach ($schools as $schoolId => $schoolName) {
            if (strpos($schoolName, $key) !== false) {
                $machIds[$schoolId] = $schoolName;
            }
        }
        return $withName ? $machIds : array_keys($machIds);
    }

    /**
     * 处理数组中id转换为名称
     *
     * @param $objArr
     * @param array $fields
     * @return bool
     *
     * create by ck 20180726
     */
    public static function runName(&$objArr, $fields = [])
    {
        if (!$objArr || !$fields) {
            return false;
        }
        is_string($fields) and $fields = [$fields => $fields];
        $schoolNames = self::getSchools(true);
        foreach ($objArr as $index => &$obj) {
            foreach ($fields as $idField => $nameField) {
                if (!isset($schoolNames[$obj[$idField]])) {
                    continue;
                }
                $obj[$nameField] = $schoolNames[$obj[$idField]];
            }
        }
        return $objArr;
    }

    /**
     * 处理数组中id转换为编号
     *
     * @param $objArr
     * @param array $fields
     * @return bool
     *
     * create by ck 20181016
     */
    public static function runCode(&$objArr, $fields = [])
    {
        if (!$objArr || !$fields) {
            return false;
        }
        is_string($fields) and $fields = [$fields => $fields];
        $schoolCodes = self::getCodes(true);
        foreach ($objArr as $index => &$obj) {
            foreach ($fields as $idField => $codeField) {
                if (!isset($schoolCodes[$obj[$idField]])) {
                    continue;
                }
                $obj[$codeField] = $schoolCodes[$obj[$idField]];
            }
        }
        return $objArr;
    }

    /**
     * 刷新缓存
     *
     * create by ck 20180612
     */
    public static function refresh()
    {
        Cache::delete('school_list');
        Cache::delete('school_support');
        Cache::delete('school_code_list');
        Cache::delete('school_code_support');
    }

    /**
     * 获取学校权限
     *
     * @param bool $withName
     * @param null $userId
     * @throws XhException
     * @return array|bool
     *
     * create by ck 20180611
     * modify by ck 20180822
     * modify by ck 20180930
     */
    public static function getPower($withName = false, $userId = null)
    {
        $userId or $userId = User::getId();
        if ($userId == User::getId() && User::isAdmin()) {
            return true;
        }
        $schoolIds = Power::getExtraPower('school', 'main', $userId);
        if ($schoolIds === true) {
            return true;
        }
        if (Main::getLoginUserInfo('userType') == 4) {
            $schoolIds[] = Main::getLoginUserInfo('schoolId');
        }
        if ($withName && $schoolIds) {
            $schoolArr = self::getSchools();
            $newSchoolArr = [];
            foreach ($schoolIds as $schId) {
                $newSchoolArr[$schId] = $schoolArr[$schId];
            }
            $schoolIds = $newSchoolArr;
        }
        return $schoolIds;
    }

    /**
     * 获取学校合并权限（交集）
     *
     * @param $targetId
     * @param bool $withName
     * @throws XhException
     * @return array|bool
     *
     * create by ck 20180612
     */
    public static function getMergePower($targetId, $withName = false)
    {
        if ($targetId == User::getId()) {
            return self::getPower($withName);
        }
        $schoolPower1 = self::getPower($withName);
        if ($schoolPower1 === true) {
            return self::getPower($withName, $targetId);
        }
        $schoolPower2 = self::getPower($withName, $targetId);
        if ($schoolPower2 === true) {
            return $schoolPower1;
        }
        return array_intersect($schoolPower1, $schoolPower2);
    }

    /**
     * 检查是否有学校权限
     *
     * @param $schoolId
     * @param bool $manage
     * @throws XhException
     * @return bool
     *
     * create by ck 20180611
     */
    public static function hasPower($schoolId, $manage = false)
    {
        return Power::hasExtra('school', 'main', $schoolId, $manage);
//        $schoolIds = $manage ? Power::getExtraPower('school', 'main') : self::getPower();
//        if ($schoolIds === true) {
//            return true;
//        }
//        return in_array($schoolId, $schoolIds);
    }

    /**
     * 获取指定学校id下面的老师
     *
     * @param $schoolId
     * @param bool $withName
     * @return array
     *
     * create by xjq 20180704
     */
    public static function getTchBySchoolId($schoolId, $withName = false)
    {
        $teachers = XhsysUser::find([
            'columns' => 'iUserId , sUserName',
            'conditions' => 'iSchoolId = :schoolId: and bDelete= 0 and bDisable = 0 and bHistory = 0 and iUserType = 4',
            'bind' => ['schoolId' => $schoolId]
        ])->toArray();
        return $withName ? array_column($teachers, 'sUserName', 'iUserId') : array_column($teachers, 'iUserId');
    }

    /**
     * 检查学校是否已审核
     *
     * @param $schoolId
     * @return bool
     *
     * create by ck 20180905
     */
    public static function isApproval($schoolId)
    {
        $school = XhschoolInfo::findFirst([
            'columns' => 'iApprovalStatus',
            'conditions' => 'iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId]
        ]);
        return $school ? !!$school->iApprovalStatus : false;
    }

    /**
     * 设置学校编号
     *
     * @param $schoolId
     * @param $code
     * @throws XhException
     *
     * create by ck 20181026
     */
    public static function setSchoolCode($schoolId, $code)
    {
        $school = XhschoolInfo::findFirst($schoolId);
        if (!$school) {
            throw new XhException('学校不存在');
        }
        //检查code是否已存在
        $count = XhschoolInfo::count([
            'conditions' => 'bDelete = 0 AND sCode = :code: AND iSchoolId <> :schoolId:',
            'bind' => ['code' => $code, 'schoolId' => $schoolId]
        ]);
        if ($count) {
            throw new XhException('该编号已存在，请检查');
        }

        $school->sCode = $code;
        if (!$school->save()) {
            throw new XhException('编号保存失败', $school->getError());
        }
    }

    /**
     * 转学（重构）
     *
     * @param $userIdArr
     * @param $schoolId
     * @param null $class
     * @return bool
     * @throws \Exception
     *
     * create by sqb 20190222
     */
    public static function changeSchool($userIdArr, $schoolId, $class = null)
    {
        if (!$userIdArr) {
            throw new \Exception('用户id不能为空');
        }

        if (!$schoolId) {
            throw new \Exception('请选择学校');
        }

        foreach ($userIdArr as $userId) {
            $history = XhsysUserHistory::find([
                'conditions' => 'iUserId = :userId: and bDelete = 0',
                'columns' => 'iChangeStatus',
                'bind' => ['userId' => $userId],
                'order' => 'iId desc',
                'limit' => 1
            ])->toArray();

            if ($history && ! $history[0]['iChangeStatus']) {
                throw new \Exception('该用户转校中，请勿重复提交');
            }
        }

        try {
            $inInfo = json_encode(['schoolId' => $schoolId, 'year' => date('Y'), 'class' => $class]);//转入后信息
            foreach ($userIdArr as $userId) {
                $userObj = Charge::getUserInfo($userId);
                $beforeSchoolId = $userObj->iSchoolId;
                $userCreateTime = $userObj->tCreateDate;
                $beforeClass = $userObj->sAdClsName;
                $beforeYear = '20' . substr($beforeClass, 0, 2);
                $outInfo = json_encode(['schoolId' => $beforeSchoolId, 'year' => $beforeYear, 'class' => $beforeClass]);//转出前信息
                $userHistoryModel = new XhsysUserHistory();
                $userHistoryModel->iUserId = $userId;
                $userHistoryModel->tTime = date('Y-m-d H:i:s');
                $userHistoryModel->tUserCreateTime = $userCreateTime;
                $userHistoryModel->sOutInfo = $outInfo;
                $userHistoryModel->sInInfo = $inInfo;
                $userHistoryModel->save();
            }

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取转校记录
     *
     * @param null $changeStatus
     * @param null $status
     * @param null $userId
     * @return array
     * @throws \Exception
     *
     * create by sqb 20190226
     */
    public static function getChangeSchoolList($changeStatus = null, $status = null, $userId = null)
    {
        $conditions = 'bDelete = 0';
        if ($userId) {
            $conditions .= ' and iUserId = '.$userId;
        }
        if ($status == 0 && $status !== null) {
            $conditions .= ' and iStatus = 0';
        }
        if ($status == 1) {
            $conditions .= ' and iStatus = 1';
        }
        if ($changeStatus == 1) {
            $conditions .= " AND iChangeStatus = 1";
        } else if ($changeStatus == 0 && $changeStatus !== null) {
            $conditions .= " AND iChangeStatus = 0";
        }
        try {
            $list = XhsysUserHistory::find([
                'conditions' => $conditions,
                'order' => 'iId desc'
            ]);
            $schoolIds = School::getPower();
            if ($list) {
                $grade = [1 => '小学', 2 => '初中', 3 => '高中'];
                $check = [0 => '未审核', 1 => '已审核'];
                $status = [0 => '转校中', 1 => '已转校'];
                $type = [1 => '学生', 4 => '老师'];
                $list = $list->toArray();
                $data = [];
                foreach ($list as $item) {
                    //处理老数据
                    if ($item['iSchoolId']) {
                        continue;
                    }
                    $item['sStatusName'] = $check[$item['iStatus']];
                    $item['sChangeStatusName'] = $status[$item['iChangeStatus']];
                    $outInfo = json_decode($item['sOutInfo'], true);
                    $inInfo = json_decode($item['sInInfo'], true);
                    if ($schoolIds !== true && (!in_array($outInfo['schoolId'], $schoolIds) || !in_array($inInfo['schoolId'], $schoolIds))) {
                        continue;
                    }
                    //上一所学校
                    $schoolInfo = XhschoolInfo::findFirst([
                        'columns' => 'sSchoolName,iStage',
                        'conditions' => 'bDelete = 0 and iSchoolId = :schoolId:',
                        'bind' => ['schoolId' => $outInfo['schoolId']]
                    ]);
                    $outInfo['schoolName'] = $schoolInfo->sSchoolName;
                    $outInfo['grade'] = $grade[$schoolInfo->iStage];
                    //当前学校
                    $schoolInfo = XhschoolInfo::findFirst([
                        'columns' => 'sSchoolName,iStage',
                        'conditions' => 'bDelete = 0 and iSchoolId = :schoolId:',
                        'bind' => ['schoolId' => $inInfo['schoolId']]
                    ]);
                    $inInfo['schoolName'] = $schoolInfo->sSchoolName;
                    $inInfo['grade'] = $grade[$schoolInfo->iStage];

                    $item['sOutInfo'] = $outInfo;
                    $item['sInInfo'] = $inInfo;
                    $item['outSchool'] = $outInfo['schoolName']."（<span>学段：{$outInfo['grade']}</span><span style='margin-left: 15px;'>班级：{$outInfo['class']}</span><span style='margin-left: 15px;'>年份：{$outInfo['year']}</span>）";
                    $item['inSchool'] = $inInfo['schoolName']."（<span>学段：{$inInfo['grade']}</span><span style='margin-left: 15px;'>班级：{$inInfo['class']}</span><span style='margin-left: 15px;'>年份：{$inInfo['year']}</span>）";

                    $userInfo = XhsysUser::findFirst($item['iCreateUserId']);
                    $item['iCreateUserName'] = $userInfo->sUserName;

                    $userInfo = XhsysUser::findFirst($item['iUserId']);
                    $item['sUserName'] = $userInfo->sUserName;
                    $item['sLoginName'] = $userInfo->sLogonName;
                    $item['iType'] = $type[$userInfo->iUserType];
                    $data[] = $item;
                }

                return $data;
            }
            return [];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}
